package com.xgy.userauthsystem.controller;

import com.xgy.userauthsystem.dto.ApiResponse;
import com.xgy.userauthsystem.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 验证码控制器
 * 处理验证码的生成和验证
 */
@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {

    private final CaptchaService captchaService;// 验证码服务

    // 构造函数，注入验证码服务
    @Autowired
    public CaptchaController(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    /**
     * 获取验证码图片
     * @return 验证码图片和ID
     */
    @GetMapping("/generate")
    public ResponseEntity<ApiResponse<Map<String, String>>> generateCaptcha() {
        System.out.println("收到验证码生成请求");
        
        // 生成唯一的验证码ID
        String captchaId = UUID.randomUUID().toString();
        
        // 生成验证码
        String[] captchaData = captchaService.generateCaptcha(captchaId);
        String captchaImage = captchaData[0];
        
        // 构造返回数据
        Map<String, String> responseData = new HashMap<>();
        responseData.put("captchaId", captchaId);
        responseData.put("captchaImage", "data:image/png;base64," + captchaImage);
        
        System.out.println("验证码生成成功，ID: " + captchaId);
        return ResponseEntity.ok(ApiResponse.success("验证码生成成功", responseData));
    }
}